package 算法.练习1;

import 算法.NiuKe.ListNode;

import java.util.List;

/**
 * @author:谢君臣
 * @Date:2021/8/15-9:39
 * @version:1.0
 * @function:
 */
public class NC40 {
    public static void main(String[] args) {

    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        StringBuilder num1 = new StringBuilder();
        StringBuilder num2 = new StringBuilder();
        while (head1!=null){num1.append(head1.val); head1 = head1.next;}
        while (head2!=null){num2.append(head2.val); head2 = head2.next;}
        StringBuilder num = Num_sum(num1,num2);
        int n =num.length();
        while (n>0){
            ListNode node = new ListNode(num.charAt(--n)-'0');
            node.next = head1;
            head1 = node;
        }
        return head1;
    }

    private StringBuilder Num_sum(StringBuilder num1, StringBuilder num2) {
        StringBuilder res = new StringBuilder();
        int i = 1,k=0,L1 = num1.length(),L2 = num2.length();
        while (i<=L1&&i<=L2){
            int temp = (num1.charAt(L1-i)-'0')+ (num2.charAt(L2-i)-'0')+ k;
            res.append(temp%10);
            k = temp/10;
            i++;
        }
        while (i<=L1){
            int temp = (num1.charAt(L1-i)-'0')+ k;
            res.append(temp%10);
            k = temp/10;
            i++;
        }
        while (i<=L2){
            int temp = (num2.charAt(L2-i)-'0')+ k;
            res.append(temp%10);
            k = temp/10;
            i++;
        }
        if (k>0)res.append(k);
        return res.reverse();
    }
}
